package br.biofoco.p2p.rpc.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import br.biofoco.p2p.rpc.EndPoint;
import br.biofoco.p2p.rpc.Protocol;
import br.biofoco.p2p.rpc.messaging.CommandHandler;
import br.biofoco.p2p.rpc.messaging.Transport;
import br.biofoco.p2p.rpc.messaging.TransportClient;

public class HttpTransportServer implements Transport {	
	
	private volatile boolean isRunning;

	private final int port;
	private HttpServer server;
	
	public HttpTransportServer(int port) {
		this.port = port;
		
	}

	@Override
	public TransportClient createClient(EndPoint endpoint) throws Exception {
		throw new UnsupportedOperationException("Operation not supported");
	}

	@Override
	public Protocol getProtocol() {
		return Protocol.HTTP;
	}

	@Override
	public boolean isActive() {
		return isRunning;
	}

	@Override
	public void setCommandHandler(CommandHandler handler) {
		throw new UnsupportedOperationException("Operation not supported");		
	}

	@Override
	public void start() throws Exception {
	    InetSocketAddress addr = new InetSocketAddress(port);
	    server = HttpServer.create(addr, 0);

	    server.createContext("/", new MyHandler());
	    server.setExecutor(Executors.newCachedThreadPool());
	    server.start();
		
	}

	@Override
	public void stop() throws Exception {
		server.stop(0);	
	}
	
	class MyHandler implements HttpHandler {
		  public void handle(HttpExchange exchange) throws IOException {
		    String requestMethod = exchange.getRequestMethod();
		    if (requestMethod.equalsIgnoreCase("GET")) {
		      Headers responseHeaders = exchange.getResponseHeaders();
		      responseHeaders.set("Content-Type", "text/plain");
		      exchange.sendResponseHeaders(200, 0);

		      OutputStream responseBody = exchange.getResponseBody();
		      Headers requestHeaders = exchange.getRequestHeaders();
		      Set<String> keySet = requestHeaders.keySet();
		      Iterator<String> iter = keySet.iterator();
		      while (iter.hasNext()) {
		        String key = iter.next();
		        List values = requestHeaders.get(key);
		        String s = key + " = " + values.toString() + "\n";
		        responseBody.write(s.getBytes());
		      }
		      responseBody.write("Hello World".getBytes());
		      responseBody.close();
		    }
		  }
	}	

}
